package com.thread.n4;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

//模拟多人买票
@Slf4j(topic = "c.ExerciseSell")
public class ExerciseSell {
    public static void main(String[] args) throws InterruptedException {
        TicketWindow window=new TicketWindow(1000);
        //所有线程的集合
        List<Thread>threadList=new ArrayList<>();
        //卖出票数统计
        List<Integer>amountList=new Vector<>();
        for (int i = 0; i < 4000; i++) {
            Thread thread=new Thread(()->{
                int sellCount = window.sell(randomAmount());
                try {
                    Thread.sleep(randomAmount());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                amountList.add(sellCount);
            });
            threadList.add(thread);
            thread.start();
        }
        for (Thread thread : threadList) {
            thread.join();
        }
        log.debug("剩余票{}",window.getCount());
        log.debug("卖出票{}",amountList.stream().mapToInt(i->i).sum());
    }
    static Random random=new Random();
    public static int randomAmount(){
        return random.nextInt(5)+1;
    }
}
class TicketWindow{
    private int count;
    public TicketWindow(int count){
        this.count=count;
    }

    public synchronized int getCount() {
        return count;
    }

    public synchronized int sell(int amount){
        if(this.count>=amount){
            this.count-=amount;
            return amount;
        }
        else{
            return 0;
        }
    }
}
